package com.xuelangyun.form.common.typeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.postgresql.util.PGobject;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

/**
 * DBJsonTypeHandler
 *
 * @author weiqing.huang
 * @version 1.0
 * @date 2024年6月18日18:22:31
 */
public class DBJsonTypeHandler extends BaseTypeHandler<JSONObject> {

    private static final PGobject jsonObject = new PGobject();


    @Override
    public JSONObject getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        Object obj = rs.getObject(columnIndex);
        String value = obj.toString();
        return JSON.parseObject(value);
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, JSONObject parameter, JdbcType jdbcType) throws SQLException {
        jsonObject.setType("json");
        jsonObject.setValue(parameter.toJSONString());
        ps.setObject(i, jsonObject);
    }

    @Override
    public JSONObject getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        Object obj = cs.getObject(columnIndex);
        String value = obj.toString();
        return JSON.parseObject(value);
    }

    @Override
    public JSONObject getNullableResult(ResultSet rs, String columnName) throws SQLException {
        Object obj = rs.getObject(columnName);
        String value = obj.toString();
        return JSON.parseObject(value);
    }

}